<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Medium\Action\Workbench\Group;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\Medium\Contract\MediumGroupContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 添加 - 动作.
 * @Controller
 */
class Store extends AbstractAction
{
    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/mediumGroup/store", methods="POST")
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];
        $name = $this->request->post('name', false);
        if (! $name) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请输入分组名称');
        }
        $client = $this->container->get(MediumGroupContract::class);
        $existData = $client->getMediumGroupsByCorpIdName($params['corpId'], $name, ['id']);
        if (! empty($existData)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '分组名称已存在');
        }

        $count = $client->countMediumGroup($params['corpId']);
        $insertId = $client->createMediumGroup(['name' => $name, 'corp_id' => $params['corpId'], 'order' => $count++]);
        if (! $insertId) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '添加失败');
        }

        return ['id' => $insertId];
    }
}
